package com.lecture.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class DrawLineUtil {

  private static final   List<String> suffixes =
          Collections.unmodifiableList(Arrays.asList("jpg", "bmp", "jpeg", "png", "gif", "JPG", "BMP", "JPEG", "PNG", "GIF"));

    /**
     * 处理图片,返回处理的数量
     * @param imagePath
     * @return
     */
    public static int processImgs(String imagePath){
        int num=0;
        File file=null;
        if(imagePath!=null && (file= new File(imagePath)).exists()){
            if(file.isFile()){
                num+=processImg(file);
            }else if (file.isDirectory()){
                File imgFiles[] = file.listFiles();
                for (File x : imgFiles) {
                    num+=processImg(x);
                }
            }
        }
         return num;
    }

    /**
     *处理单个img
     * @param imgFile
     * @return
     */
    private static int processImg(File imgFile){
        int num=0;
        String suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
        if(suffixes.contains(suffix)){
            num= addLineColor(imgFile)?++num:num;
        }
        return num;
    }


    /**
     * 图片添加3像素红色边框
     * @param srcFile
     * @throws Exception
     */
    private   static boolean addLineColor(File srcFile)  {
        boolean flag=false;
        //读取源文件
        try {
            BufferedImage srcImg = ImageIO.read(srcFile);
            Graphics2D graphics = srcImg.createGraphics();
            //画水平线
            graphics.setColor(Color.RED);
            //线像素
            Stroke stroke=new BasicStroke(3.0f);//设置线宽为3.0
            graphics.setStroke(stroke);
            //上框
            graphics.drawLine(1,1,srcImg.getWidth()-1,1);
            graphics.drawLine(1,srcImg.getHeight()-1,srcImg.getWidth()-1,srcImg.getHeight()-1);
            graphics.drawLine(1,1,1,srcImg.getHeight()-1);
            graphics.drawLine(srcImg.getWidth()-1,1,srcImg.getWidth()-1,srcImg.getHeight()-1);

            String oldName = srcFile.getName();
            String absolutePath = srcFile.getAbsolutePath();
            String suffix= oldName.substring(oldName.lastIndexOf(".") + 1);
            ImageIO.write(srcImg, suffix, new File(absolutePath));
            flag=true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

//    public static void main(String[] args) {
//        String imgPath="C:\\Users\\Administrator\\Desktop\\imgs\\Snipaste_2020-11-21_12-17-23.png";
//        int count = processImgs(imgPath);
//        System.out.println("count:"+count);
//    }
}
